#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/time.h>
#include <sys/stat.h>

#include "data_type.h"
#include "alloc.h"
#include "errno.h"
#include "memfunc.h"
#include "basefunc.h"
#include "struct_deal.h"
#include "crypto_func.h"
#include "memdb.h"
#include "message.h"
#include "ex_module.h"

int echo_init(void * sub_proc,void * para)
{
	int ret;
	// add youself's plugin init func here
	return 0;
}

int echo_start(void * sub_proc,void * para)
{

	int ret;
	void * recv_msg;
	int i;
	int type;
	int subtype;
	proc_echo_message(sub_proc, para);

	// while(1)
	// {
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			return 0;
		if(recv_msg==NULL)
			return 0;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			ex_module_sendmsg(sub_proc,recv_msg);
			return 0;
		}
		if((type==DTYPE_MESSAGE)&&(subtype==SUBTYPE_CTRL_MSG))
		{
			ret=proc_ctrl_message(sub_proc,recv_msg);
			if(ret==MSG_CTRL_EXIT)
				return MSG_CTRL_EXIT;
		}
		else
		{
			ex_module_sendmsg(sub_proc,recv_msg);
			//proc_echo_message(sub_proc,recv_msg);
		}
	//}
	return 0;
};

int proc_echo_message(void * sub_proc,void * message)
{
	int type;
	int subtype;
	int i;
	int ret;
	//printf("begin proc echo \n");

	type=message_get_type(message);
	subtype=message_get_subtype(message);

	void * new_msg;
	void * record;
	new_msg=message_create(type,subtype,message);
	
	i=0;

	ret=message_get_record(message,&record,i++);
	if(ret<0)
		return ret;
	while(record!=NULL)
	{
		message_add_record(new_msg,record);
		ret=message_get_record(message,&record,i++);
		if(ret<0)
			return ret;
	}

	ex_module_sendmsg(sub_proc,new_msg);

	return ret;
}

int proc_ctrl_message(void * sub_proc, void * recv_msg)
{
	int ret;
	struct ctrl_message * ctrl_msg;
	ctrl_msg=Talloc0(sizeof(*ctrl_msg));
	if(ctrl_msg==NULL)
		return -CUBEERR_NOMEM;
	ctrl_msg->name=dup_str(ex_module_getname(sub_proc),0);
	ctrl_msg->ctrl=MSG_CTRL_EXIT;
	void * new_msg;
	new_msg=message_create(DTYPE_MESSAGE,SUBTYPE_CTRL_MSG,recv_msg);
	if(new_msg==NULL)
		return -CUBEERR_INVAL;
	ret=message_add_record(new_msg,ctrl_msg);
	if(ret<0)
		return ret;
	ret=ex_module_sendmsg(sub_proc,new_msg);
	return ret;	
}

int echo_exit()
{
    return 0;
}


